package com.chengh.nami.web.controller.login;

import com.chengh.nami.common.constants.CacheConstants;
import com.chengh.nami.common.constants.Constants;
import com.chengh.nami.common.domain.model.LoginBody;
import com.chengh.nami.common.response.R;
import com.chengh.nami.common.utils.captchaImage.CaptchaImageUtils;
import com.chengh.nami.common.utils.captchaImage.model.CaptchaCodeEnum;
import com.chengh.nami.common.utils.redis.RedisCache;
import com.chengh.nami.common.utils.uuid.IdUtils;
import com.chengh.nami.core.security.service.LoginService;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户登陆类
 *
 * @author hspcadmin
 */
@Slf4j
@RestController
@RequestMapping("/login")
@RequiredArgsConstructor
public class LoginController {

    private final LoginService loginService;
    private final RedisCache redisCache;

    @Resource
    private CaptchaImageUtils captchaImageUtils;

    /**
     * 登录入口的方法
     *
     * @param loginBody 登录信息
     * @return 是否成功
     */
    @PostMapping("/userLogin")
    public R<Map<String, Object>> userLogin(@RequestBody LoginBody loginBody) {
        String token = loginService.login(loginBody);
        HashMap<String, Object> hashMap = new HashMap<>(1);
        hashMap.put("token", token);
        return R.ok(hashMap);
    }

    /**
     * 获取验证码信息
     *
     * @return 验证码信息
     */
    @GetMapping("/captchaImage")
    public R<Map<String, Object>> captchaImage() {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        Captcha captcha = captchaImageUtils.getCaptcha();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == CaptchaCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(Constants.DOP)) {
            captchaValue = captchaValue.split("\\.")[0];
        }

        int i = RandomUtils.nextInt(5, 10);
        redisCache.setCacheObject(verifyKey, captchaValue, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("uuid", uuid);
        hashMap.put("img", captcha.toBase64());
        return R.ok(hashMap);
    }

}
